package services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import repositories.AdministratorRepository;
import security.Authority;
import security.LoginService;
import security.UserAccount;
import domain.Administrator;
import forms.AdminForm;

@Service
@Transactional
public class AdministratorService {
	@Autowired
	private AdministratorRepository administratorRepository;

	public AdministratorService() {
		super();
	}

	public Administrator create() {
		Administrator administrator = new Administrator();
		Authority auth = new Authority();
		auth.setAuthority("ADMINISTRATOR");
		UserAccount userAccount = new UserAccount();
		userAccount.addAuthority(auth);
		administrator.setUserAccount(userAccount);

		return administrator;
	}

	public void save(Administrator administrator) {
		Assert.notNull(administrator);
		
		administratorRepository.save(administrator);
	}

	public Administrator findByPrincipal() {
		Administrator result;
		UserAccount userAccount;

		userAccount = LoginService.getPrincipal();
		Assert.notNull(userAccount);
		result = findByUserAccount(userAccount);
		Assert.notNull(result);

		return result;
	}

	public Administrator findByUserAccount(UserAccount userAccount) {
		Assert.notNull(userAccount);

		Administrator result;

		result = administratorRepository.findByUserAccountId(userAccount
				.getId());

		return result;
	}
	//Reconstruction method
	public Administrator reconstruct(AdminForm adminForm){
		Administrator result = create();
		result.getUserAccount().setUsername(adminForm.getUsername());
		result.getUserAccount().setPassword(adminForm.getPassword());
		result.setName(adminForm.getName());
		result.setSurname(adminForm.getSurname());
		result.setEmail(adminForm.getEmail());
		
		
		return result;
	}
}
